package com.hp.bon.sgw.wh.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * 加验签工具类
 * 
 * @author suxinj
 */
//public class SignUtilsImpl implements SignUtils {
public class SignUtilsImpl  {
	private final static Logger _log = LoggerFactory.getLogger(SignUtilsImpl.class);
/*	public static void main(String[] args) {
		String body="189861379735000SIGNBalanceAlert20140522 15:22:16我爱你中国";
		//String singTag="s79eVfQd0yS/V4ZKmTLMb3FdGeH6wTeSFktabHThQ+WRPiFACi7wJSllM1GZz0yA32DEL4IZWAqXgHydoN9IWP2mcSySQInubQ+veMinZqxNGF/s3jSsQZlsuQVMoOC+5ft056p3zcCZifQEtzYT6TcdZPNuyQ3B12ZIG4qQviA=";
		String singTag = "PuClFm75zljzj+EKfOEo1JofrbdZxtpxYTcDwDsPhqrMypQZ0rQg4MJNxL033cxM4p20LJlJjA5mKswObgGEjf6cX+Sp3vFI0jBJRLtBo6pbUg0PVdXvLbyMrf8+Iaq/aCmgdtVp6ughkqqFa20c/D19RYnepWMPriFErfeuBK4=";
		String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLjMwWgWD2g4v2XOt39ukZ0Uxa1r/Kh4zMdXB6K5PY2fwwcipqEzycdnhfnf81V0oOcW2vVWpnFpDlsqNfDEPTaDxoCCHOOzQoi999q+biF14oJSSFZ71fefC9vxc1o2zl0CHkBD+DeE86+HxpaE2GEcs4yXSmdPN2AcKMYHBKrwIDAQAB";
		System.out.println(verify(body, singTag, pubKey, "SHA1withRSA","utf-8"));
	}*/

	/**
	 * 加签
	 * 
	 * @param text
	 *            明文
	 * @param key
	 *            密钥
	 * @param algorithm
	 *            签名算法,目前KMI支持NONEwithRSA, MD2withRSA, MD5withRSA, SHA1withRSA,
	 *            SHA256withRSA, SHA384withRSA, SHA512withRSA , SHA1withDSA
	 * @return 签名
	 * @throws Exception
	 */
	public static String sign(final String text, final String key, final String algorithm ,final String charset) {
		final byte[] keyBytes = Base64.decode(key);
		byte[] resultBytes = null;
		try {
			final byte[] textBytes = text.getBytes(charset);
			resultBytes = SignatureUtil.sign(textBytes, keyBytes, algorithm);
			return Base64.encode(resultBytes);
		} catch (GeneralSecurityException e) {
			System.out.println("加签异常："+e);
			return "";
		} catch (UnsupportedEncodingException e) {
			System.out.println("不支持的编码方式:"+e);
			return "";
		}

	}

	/**
	 * 验签
	 * 
	 * @param text
	 *            明文
	 * @param signText
	 *            签名
	 * @param key
	 *            密钥
	 * @param algorithm
	 *            验签算法,目前KMI支持NONEwithRSA, MD2withRSA, MD5withRSA, SHA1withRSA,
	 *            SHA256withRSA, SHA384withRSA, SHA512withRSA , SHA1withDSA
	 * @return 验签通过返回true，不通过返回false
	 * @throws Exception
	 */
	public static  boolean verify(final String text, final String signText,
			final String key, final String algorithm, final String charset) {

		try {
			return SignatureUtil.verify(text.getBytes(charset),
					Base64.decode(signText), Base64.decode(key), algorithm);
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * @see com.hp.bon.sgw.wh.utils.test.common.crypto.alipay.virtualprod.common.crypto.SignUtils#encrypt(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	public static String encrypt(String text, String key, String algorithm) {

		byte[] bytes = text.getBytes(); // 待加/解密的数据
		byte[] keyData = Base64.decode(key); // 密钥数据

		try {
			byte[] cipherBytes = SymmtricCryptoUtil.symmtricCrypto(bytes,
					keyData, algorithm, Cipher.ENCRYPT_MODE);
			return Base64.encode(cipherBytes);
		} catch (GeneralSecurityException e) {
			return "";
		}
	}

	/**
	 * @see com.hp.bon.sgw.wh.utils.test.common.crypto.alipay.virtualprod.common.crypto.SignUtils#decrypt(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	public static String decrypt(String text, String key, String algorithm) {

		byte[] bytes = Base64.decode(text); // 待加/解密的数据
		byte[] keyData = Base64.decode(key); // 密钥数据

		try {
			byte[] cipherBytes = SymmtricCryptoUtil.symmtricCrypto(bytes,
					keyData, algorithm, Cipher.DECRYPT_MODE);
			return new String(cipherBytes);
		} catch (GeneralSecurityException e) {
			return "";
		}
	}
	
	public static String getTmallSign(String str)
	{
		String md5Str = "";
		if (str != null && str.length() != 0) {
			try {
				MessageDigest md = MessageDigest.getInstance("MD5");
				md.update(str.getBytes("gbk"));
				byte b[] = md.digest();
				int i;
				StringBuffer buf = new StringBuffer("");
				for (int offset = 0; offset < b.length; offset++) {
					i = b[offset];
					if (i < 0)
						i += 256;
					if (i < 16)
						buf.append("0");
					buf.append(Integer.toHexString(i));
				}
				md5Str = buf.toString();
			    
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e2) {
				e2.printStackTrace();
			}
		}
		return md5Str;
	}
	
	public static boolean checkTmallSign(String str,String sign) {
		String md5Str = "";
		if (str != null && str.length() != 0) {
			try {
				MessageDigest md = MessageDigest.getInstance("MD5");
				md.update(str.getBytes("gbk"));
				byte b[] = md.digest();
				int i;
				StringBuffer buf = new StringBuffer("");
				for (int offset = 0; offset < b.length; offset++) {
					i = b[offset];
					if (i < 0)
						i += 256;
					if (i < 16)
						buf.append("0");
					buf.append(Integer.toHexString(i));
				}
				md5Str = buf.toString();
			    
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e2) {
				e2.printStackTrace();
			}
		}
		_log.info("SGW sign = {}",md5Str);
		return md5Str.equals(sign);
	}
}
